package com.personal.dao.sqlgenerator;

import com.personal.dao.configuration.Configuration;
import com.personal.dao.exception.ValidatorNotPassException;
import com.personal.dao.metadata.DataBaseFieldMetadata;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.metadata.ValidatorMetadata;
import com.personal.dao.reflection.MetaObject;
import com.personal.dao.util.DaoUtil;

/**
 * 生成sql对数据校验
 * 校验实现，暂时简单实现
 * 后期可以扩展使用personal-validate实现复杂的业务校验
 * @author qq
 *
 */
public class SqlValidator
{
    public static <T> void validate(DataBaseTableMetadata<T> metadata, T value, MetaObject valueMeta)
    {
    	if (valueMeta == null)
		{
			valueMeta =  Configuration.getInstance().newMetaObject(value);
		}
    	if (metadata.getPrimaryKey() != null)
		{
			validateSingleField(metadata.getPrimaryKey(), value, valueMeta);
		}
    	for (DataBaseFieldMetadata field : metadata.getFields())
		{
    		validateSingleField(field, value, valueMeta);
		}
    }
    
    private static <T> void validateSingleField(DataBaseFieldMetadata field, T value, MetaObject valueMeta)
    {
    	ValidatorMetadata validator = field.getValidator();
    	if (validator == null)
		{
			return;
		}
    	if (validator.getMaxLength() > -1)
		{
			Object obj = valueMeta.getValue(field.getFieldName());
			if (obj == null)
			{
				return;
			}
			if (obj.toString().length() > validator.getMaxLength())
			{
				throw new ValidatorNotPassException(DaoUtil.isEmpty(validator.getErrorMessage()) ? field.getCaption() + "的长度不能超过：" + validator.getMaxLength() : validator.getErrorMessage());
			}
		}
    }
}
